#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   GameEffect
@Time    :   2023/03/31 23:06:43
@author  :   Eval
@Version :   1.0
@Describe:   游戏特效处理
'''
from lib.scripts.GC import *
from conf.GameLogin import *
import os,pygame
from random import randint

class Effect:
    def __init__(self,parent) -> None:
        from lib.run import Run
        self.parent:Run = parent
        self.path = "lib/images/effect"
        self.effects = {}  # 特效集
        self.render_eff:list[EffSrpite] = []  # 遍历播放特效数组 , 当特效的生命周期结束后,从这个列表删除
        self.nowPlayEff = False  # 当前是否正在播放动画
        
        self.__loadEffect(self.path)
        
    def __loadEffect(self,path):
        """私有方法 使用递归加载所有的特效文件,使用特效文件的当前目录名当作特效的名称"""
        if not os.path.exists(path):
            print_error(f"不存在的动画路径:{path}")
            self.parent.GameLoad.tips = f"不存在的动画路径:{path}"
            return 
        dirArr = os.listdir(path)
        effArr = []
        effName = ""
        effSize = 0


        for file in dirArr:
            if(os.path.isfile(path+"/"+file)):
                if file.endswith(".txt"):
                    continue
                effName = path.split("/").pop()
                effSize += round(int(os.path.getsize(path+"/"+file))/1024,2)
            else:
                self.__loadEffect(path+"/"+file)
        if effName == "":
            return
        # 判断配置文件是否存在
        if not os.path.exists(path+f"/{effName}.txt"):
            print_error(f"配置文件:{effName}.txt 不存在")
            self.parent.GameLoad.tips = f"配置文件:{effName}.txt 不存在"
            return
        else:
            with open(path+f"/{effName}.txt","r") as f:
                resArr = f.readlines()
                for i in resArr:
                    if i.startswith("#"):
                        continue
                    if i.isspace():
                        continue
                    name = i.replace("\n","")
                    effArr.append(GC.loadSurface(effName+"^"+name,path+"/"+name))
                    
        self.effects[effName] = {
            "images":effArr,  # 用于存放原始的精灵
            "size":effSize
        }
        self.parent.GameLoad.tips = f"加载特效:{effName} 完成!"
        # print_info(f"加载特效:{effName} 完成!")

    def render(self):
        """渲染特效"""
        if not len(self.render_eff):
            return
        
        for eff in self.render_eff:
            if eff.index >= eff.length:
                self.render_eff.remove(eff)
                continue
            eff.update(self.parent.win)
            if self.parent.GInit.delay % 5:
                break
            eff.index += 1
        if not len(self.render_eff):
            self.nowPlayEff = False

    
    def playEffect(self,effName,x=0,y=0,size:int=None):
        """根据特效名称得到特效 并添加到渲染列表中"""
        effData = self.effects.get(effName)
        if effData is None:
            return
        self.nowPlayEff = True
        eff = EffSrpite(effName,effData["images"],effData["size"],[x,y])
        if size is not None:
            for img in eff.images:
                eff.render_img.append(pygame.transform.smoothscale(img.copy(),(size,size)))
                eff.rect.width = size
                eff.rect.height = size
        else:
            for img in eff.images:
                eff.render_img.append(img.copy())

        self.render_eff.append(eff)

    def randPlayEff(self,x,y,size:int=None):
        """随机播放特效"""
        keys = list(self.effects.keys())
        self.playEffect(keys[randint(0,len(keys)-1)],x,y,size)

    def print_effects(self):
        """打印当前加载的特效数据"""
        for eff in self.effects:
            effect = self.effects[eff]
            print_debug(f'名称:{effect["effName"]},长度:{effect["length"]},总大小:{effect["size"]} KB')


class EffSrpite:
    def __init__(self,effName:str,effArr:list[pygame.Surface],effSize:int,pos:list[int,int]) -> None:
        self.effName:str  = effName
        self.length:int  = len(effArr)
        self.images:list[pygame.Surface] = effArr # 用于存放原始的精灵,不对这个对象做修改,以及渲染
        self.render_img:list = []
        self.rect = self.images[0].get_rect()
        self.size:float  = effSize
        self.x:int  = pos[0]
        self.y:int  = pos[1]
        self.pos:list[int,int] = pos
        self.index:int = 0

    def update(self,win):
        win.blit(self.render_img[self.index],(self.x,self.y-self.rect.height//2))